package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.service.INavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class NavServiceImpl implements INavService {
    @Override
    public List<NavModel> getNavModelList() {
        NavDao navDao = new NavImpl();
        /**
         * 1.判断当前缓存里面是否有值
         * 有，则取缓存
         * 没有，则取数据库
         */
        Jedis jedis = new Jedis();
        jedis.select(15);
        List<NavModel> list = new ArrayList<>();
        boolean boo = jedis.exists("navListHref");
        if (boo) {
            long length = jedis.llen("navListHref");
            for (int i = 0; i < length; i++) {
                NavModel model = new NavModel();
                model.setHref(jedis.lindex("navListHref", i));
                model.setTitle(jedis.lindex("navListTitle", i));
                list.add(model);
            }
        } else {
//            数据库：封装到缓存
            list = navDao.getNavModelList();
            for (int i = 0; i < list.size(); i++) {
                jedis.rpush("navListHref", list.get(i).getHref());
                jedis.rpush("navListTitle", list.get(i).getTitle());
            }

        }
        return list;
    }

    public int update(NavModel navModel) {
        NavDao navDao = new NavImpl();
        int result = navDao.update(navModel);
        if (result == 1) {
            Jedis jedis = new Jedis();
            jedis.del("navListHref");
            jedis.del("navListTitle");
        }
        return result;
    }
}
